from pymysql import connect

from ecshop.utils.Config import Config


class MySQLHelper():
    file = '../config/config.ini'  # 文件路径为自己的包路径
    config = Config(file)
    def __init__(self):
        self.host=self.config.get_value(self.file, 'system', 'host')
        self.user=self.config.get_value(self.file, 'system', 'user')
        self.password=self.config.get_value(self.file, 'system', 'password')
        self.database=self.config.get_value(self.file, 'system', 'database')
        self.port=int(self.config.get_value(self.file, 'system', 'port'))

    def get_conn(self):
        conn = connect(user=self.user, password=self.password, host=self.host, database=self.database, port=self.port)
        return conn

    def get_cursor(self):
        cursor = self.get_conn().cursor()
        return cursor

    def select(self,sql,flag='all',number=2):
        cursor = self.get_cursor()
        cursor.execute(sql)
        try:
            if flag=='all':
                result = cursor.fetchall()
            elif flag=='one':
                result = cursor.fetchone()
            elif flag=='many':
                result = cursor.fetchmany(number)
            else:
                pass
            return result
        except Exception:
            print('只能输入:all,one,many中的一个')

    def dml(self,sql):
        cursor = self.get_cursor()
        cursor.execute(sql)

    def close(self):
        self.get_cursor().close()
        self.get_conn().close()


# mysql = MySQLHelper()
# sql = 'select goods_sn,goods_name from ecs_goods limit 0,10'
# rs = mysql.select(sql,'one')
# print(rs)
# #sql = "delete from ecs_goods where goods_name='布兰妮牌香皂'"
# #mysql.dml(sql)
# mysql.close()



